"use strict";

module.exports = exec;

const path = require("path");
const Package = require("@azir-cli/package");
const log = require("@azir-cli/log");
const spawn = require("child_process").spawn;

const settings = {
  init: "@azir-cli/init",
};

const CACHE_DIR = "dependencies/";

async function exec() {
  const cmdObj = arguments[arguments.length - 1];
  const cmdName = cmdObj.name();
  const packageName = settings[cmdName];
  const packageVersion = "latest";

  let targetPath = process.env.AZIR_CLI_TARGET_PATH;
  const cliHomePath = process.env.AZIR_CLI_HOME_PATH;

  log.debug("targetPath", targetPath);
  log.debug("cliHomePath", cliHomePath);

  let packageInst;
  if (!targetPath) {
    targetPath = path.resolve(cliHomePath, CACHE_DIR);
    const storeDir = path.resolve(targetPath, "node_modules");

    log.debug("storeDir", storeDir);

    packageInst = new Package({
      targetPath,
      storeDir,
      packageName,
      packageVersion,
    });
    if (await packageInst.exists()) {
      // 更新npm包
      const updateRes = await packageInst.update();
      if (updateRes) {
        log.success(
          `更新${packageInst.packageName}成功`,
          `version: ${packageInst.packageVersion}`
        );
      }
    } else {
      // 安装pkg
      const inistallRes = await packageInst.install();
      if (inistallRes) {
        log.success(
          `安装${packageInst.packageName}成功`,
          `version: ${packageInst.packageVersion}`
        );
      }
    }
  } else {
    packageInst = new Package({
      targetPath,
      packageName,
      packageVersion,
    });
  }
  const rootFile = packageInst.getRootFilePath();
  log.debug("rootFilePath", rootFile);
  if (rootFile) {
    try {
      const args = Array.from(arguments);
      const cmd = args[args.length - 1];
      const o = Object.create(null);
      Object.keys(cmd).forEach((key) => {
        if (
          // eslint-disable-next-line no-prototype-builtins
          cmd.hasOwnProperty(key) &&
          key !== "parent" &&
          !key.startsWith("_")
        ) {
          o[key] = cmd[key];
        }
      });
      args[args.length - 1] = o;
      const code = `require('${rootFile}').call(null, ${JSON.stringify(args)})`;
      const child = compatibleWin32Spawn("node", ["-e", code], {
        stdio: "inherit",
        cwd: process.cwd(),
      });
      child.on("error", (e) => {
        log.error(e.message);
        process.exit(1);
      });
      child.on("exit", (code) => {
        log.verbose("init命令执行成功! code: " + code);
        process.exit(code);
      });
    } catch (e) {
      log.error(e.message);
    }
  }

  //1. targetPath -> modulePath
  //2. modulePath -> Package(npm模块)
  //3. Package.getRootFile(获取入口文件)
  //3. Package.update / Package.install
}

// in windows
// spawn("cmd", ["/c", "node", "-e" ,"...code"])
function compatibleWin32Spawn(command, args, options) {
  const win32 = process.platform === "win32";
  const cmd = win32 ? "cmd" : command;
  const cmdArgs = win32 ? ["/c"].concat(command, args) : args;
  return spawn(cmd, cmdArgs, options);
}
